import { useReducer } from "react";

export default function Reducer() {
  const reducer = (state, action) => {

    // 根据不同的action type 返回新的state
    switch (action.type) {
      case "increment":
        return { count: state.count + 1 };
      case "decrement":
        return { count: state.count - 1 };
      case "update":
        return { count: action.payload };
      default:
        throw new Error("Invalid action type");
    }
  };

  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <div>
    
      <p>Count: {state.count}</p>
      <button
        style={{ marginRight: "10px", color: "#fff" }}
        onClick={() => dispatch({ type: "increment" })}
      >
        Increment
      </button>
      <button
        style={{ marginRight: "10px", color: "#fff" }}
        onClick={() => dispatch({ type: "decrement" })}
      >
        Decrement
      </button>
      <button
        style={{ color: "#fff" }}
        onClick={() => dispatch({ type: "update", payload: 100 })}
      >
        Update
      </button>
      <hr />
      <div style={{ textAlign: "left" }}>
        <ol>
          <li>定义一个reducer函数（根据不同的action返回不同的新状态）</li>
          <li>在组件中调用useReducer，并传入reducer函数和状态的初始值</li>
          <li>
            事件发生时，通过dispatch韩式分派一个action对象（通知reducer要返回哪个新状态并渲染UI）
          </li>
        </ol>
        <br />
        <br />
       <div style={{padding:20}}> useReducer 是 useState 的替代方案，useState 能做到的事，它都能做到，甚至做得更好。useReducer 某种程度上解耦了操作逻辑(action)和后续的行为(一般是 UI 的更新)，虽然代码量变多了，但是看起来更加整洁。</div>
      </div>
    </div>
  );
}
